package com.mjk.manager.amis.core.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeComplexQueryWrapper;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.util.ObjectUtils;
import com.mjk.manager.amis.core.dto.AmisCrudDTO;
import com.mjk.manager.amis.core.dto.SessionDetails;
import com.mjk.manager.amis.core.model.PlatSys;
import com.mjk.manager.amis.core.model.PlatUser;
import com.mjk.manager.amis.core.model.SysMenu;
import com.mjk.manager.amis.core.utils.SessionHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mamis/plat/sys")
public class PlatSysController {
    @Autowired
    private BeeDBService beeDBService;
    @Autowired
    private SessionHolder sessionHolder;

    @GetMapping("/list")
    public BeeResponse getSysList(
            @RequestParam(value = "status", required = false) Integer status) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatSys());
        // 查询数据库
        List<PlatSys> list = beeDBService.findManyByWrapper(wrapper);

        // 构造 amis 要求的数据结构
        final AmisCrudDTO<PlatSys> data = new AmisCrudDTO<>();
        data.setItems(list);
        // data.setTotal(platSysMapper.selectCount(wrapper));

        // 返回结果集
        return BeeError.BEE_SUC.tranceError(data);
    }
    @PostMapping()
    public BeeResponse saveSys(final HttpServletRequest request, @RequestBody final PlatSys obj) {
        SessionDetails sessionDetails = sessionHolder.getSession(request);

        int ret;
        if (StrUtil.isNotBlank(obj.getId())) {
            // 清除不可更新字段
            obj.setDELETED(null);
            obj.setCREATED_AT(null);
            obj.setCREATED_BY(null);
            obj.setUPDATED_AT(null);
            BeeQueryWrapper wrapper = new BeeQueryWrapper(obj);
            wrapper.eq(PlatSys::getId, obj.getId());
            ret = beeDBService.update(obj, wrapper);
        } else {
            obj.setSTATUS(1);
            obj.setCREATED_AT(LocalDateTime.now());
            obj.setUPDATED_AT(LocalDateTime.now());
            obj.setDELETED(false);
            ret = beeDBService.save(obj);
        }

        return ret > 0 ? BeeError.BEE_SUC.tranceError(obj) : BeeError.BEE_FAILD.tranceError();
    }

    @RequestMapping("/admin")
    public BeeResponse getAdmin(final HttpServletRequest request,
                                @RequestParam("sysId") String sysId) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatUser());
        wrapper.eq(PlatUser::getDEF_SYS_ID, sysId);
        List<PlatUser> adminList = beeDBService.findManyByWrapper(wrapper);
        String userPicker;
        if (adminList.size() > 0) {
            userPicker = adminList.stream().map(u -> u.getId()).reduce((s1, s2) -> (s1 + ',' + s2)).get();
        } else {
            userPicker = "";
        }

        Map<String, String> obj = new HashMap<>();
        obj.put("userPicker", userPicker);
        return BeeError.BEE_SUC.tranceError(obj);
    }

//    @PostMapping("/admin")
//    public ResultDTO setAdmin(final HttpServletRequest request, @RequestParam("sysId") String sysId,
//                              @RequestBody Map<String, String> body) {
//        final SessionDetails session = contextService.getSession(request);
//
//        String[] userIds = body.get("userPicker").split(",");
//        int ret = platSysService.setSysAdmins(sysId, userIds, session.getCurUserId());
//        return ret > 0 ? ResultDTO.success() : ResultDTO.error("保存失败");
//    }

    @DeleteMapping("/{id}")
    public BeeResponse delSys(final HttpServletRequest request, @PathVariable("id") String id) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatSys());
        wrapper.eq(PlatSys::getId, id);
        int ret = beeDBService.delete(wrapper);
        return ret > 0 ? BeeError.BEE_SUC.tranceError() : BeeError.BEE_FAILD.tranceError();
    }

    @GetMapping("/option/list")
    public BeeResponse getSysOptionList(
            @RequestParam(value = "status", required = false) Integer status) {
        // 查询数据库
        BeeComplexQueryWrapper wrapper = new BeeComplexQueryWrapper(new PlatSys(), "sys");
        wrapper.innerJoin(PlatSys.class, "sys1").on(PlatSys::getId, "sys", PlatSys::getId, "sys1");
        wrapper.eq(PlatSys::getDELETED, "sys", "0");
        if (ObjectUtils.isNotEmpty(status))
            wrapper.eq(PlatSys::getSTATUS, "sys", status);
        final List<PlatSys> sysList = beeDBService.findManyByComplexWrapper(wrapper);
        sysList.stream().forEach(item -> {
            item.setLabel(item.getNAME());
            item.setValue(item.getId());
        });
        // 返回结果集
        return BeeError.BEE_SUC.tranceError(sysList);
    }

    @PostMapping("/export")
    public void export(final HttpServletRequest request, final HttpServletResponse response,
                       @RequestParam("ids") String ids) throws IOException {
        // 创建导出根文件夹
        Path rootPath = Files.createTempDirectory("mamis_");
        File rootFolder = rootPath.toFile();

        // 支持多个系统一起导出
        for (String id : ids.split(",")) {
            BeeQueryWrapper wrapper = new BeeQueryWrapper(PlatSys.class);
            wrapper.eq(PlatSys::getId, id);
            PlatSys sys = (PlatSys) beeDBService.findOneByWrapper(wrapper);

            // 创建导出系统文件夹
            File sysFolder = new File(rootFolder, id);

            // 创建导出文件
            {
                File metaFile = new File(sysFolder, "meta.json");
                FileUtil.writeBytes(JSONUtil.toJsonStr(sys).getBytes(StandardCharsets.UTF_8), metaFile);
            }

            {
                File menuFile = new File(sysFolder, "menu.json");
                Map<String, Object> menuMap = new HashMap<>();
                BeeQueryWrapper wrapper1 = new BeeQueryWrapper(SysMenu.class);
                //wrapper1.eq(SysMenu::getOWN_SYS_ID, sys.getId());
                menuMap.put("menu", beeDBService.findManyByWrapper(wrapper1));
                FileUtil.writeBytes(JSONUtil.toJsonStr(menuMap).getBytes(StandardCharsets.UTF_8), menuFile);
            }

            {
                File dbFile = new File(sysFolder, "db.json");
            }
        }

        // 准备下载
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=mamis.zip");

        try (OutputStream out = response.getOutputStream()) {
            ZipUtil.zip(out, StandardCharsets.UTF_8, false, null, rootFolder);
        }

        response.setStatus(HttpServletResponse.SC_OK);
    }
}
